package com.hao.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/upload")
public class uploadController {

    @PostMapping("/img")
    public ModelAndView upload(@RequestParam MultipartFile img, HttpServletRequest request){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("index");
        String realpath=request.getSession().getServletContext().getRealPath("file");
        String name=img.getOriginalFilename();
        File file=new File(realpath,name);
        try {
            img.transferTo(file);
            modelAndView.addObject("path","/file/"+name);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return modelAndView;
    }
}
